<template>
  <view class="content"></view>
</template>

<script>
let main, receiver, filter
let _codeQueryTag = false
export default {
  data() {
    return {
      scanCode: '',
    }
  },
  created: function (option) {
    this.initScan()
    this.startScan()
  },
  onHide: function () {
    this.stopScan()
  },
  unmounted: function () {
    /* 页面退出时一定要卸载监听,否则下次进来时会重复，造成扫一次出2个以上的结果 */
    this.stopScan()
  },
  methods: {
    initScan() {
      console.log('initScan')
      try {
        const _this = this
        main = plus.android.runtimeMainActivity()
        const IntentFilter = plus.android.importClass('android.content.IntentFilter')
        filter = new IntentFilter()
        filter.addAction('nlscan.action.SCANNER_RESULT') // 换你的广播动作
        receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
          onReceive: function (context, intent) {
            console.log('main', main)
            plus.android.importClass(intent)
            console.log('intent', intent)
            const code = intent.getStringExtra('SCAN_BARCODE1') // 换你的广播标签
            _this.queryCode(code)
          },
        })
      } catch (error) {
        console.log('error', error)
      }
    },
    startScan() {
      main?.registerReceiver(receiver, filter)
    },
    stopScan() {
      main?.unregisterReceiver(receiver)
    },
    queryCode: function (code) {
      // 防重复
      if (_codeQueryTag) return false
      _codeQueryTag = true
      setTimeout(function () {
        _codeQueryTag = false
      }, 150)
      uni.$emit('scancodedate', code)
    },
  },
}
</script>
